package com.studyjava.guessdx;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class bpm extends AppCompatActivity {

    private Button tapButton;
    private TextView bpmText;
    private Button resetButton, selectMusicButton;
    private EditText detectionCountInput;
    private Switch soundSwitch;

    private long lastTapTime = 0;
    private List<Long> tapIntervals = new ArrayList<>(); // 用于存储点击间隔
    private int detectionCount = 5;  // 默认点击检测次数

    private MediaPlayer mediaPlayer;
    private SoundPool soundPool; // 声音池
    private int clickSoundId; // 点击音效的ID
    private static final int REQUEST_CODE_PICK_AUDIO = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bpm_counter);

        tapButton = findViewById(R.id.tapButton);
        bpmText = findViewById(R.id.bpmText);
        resetButton = findViewById(R.id.resetButton);
        selectMusicButton = findViewById(R.id.selectMusicButton);
        detectionCountInput = findViewById(R.id.detectionCountInput);
        soundSwitch = findViewById(R.id.soundSwitch);

        // 初始化 SoundPool
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build();

        soundPool = new SoundPool.Builder()
                .setMaxStreams(1)
                .setAudioAttributes(audioAttributes)
                .build();

        // 加载点击音效
        clickSoundId = soundPool.load(this, R.raw.click_sound, 1);

        tapButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDetectionCount();
                calculateBPM();
                if (soundSwitch.isChecked()) {
                    playClickSound();
                }
            }
        });

        resetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetBPM();
            }
        });

        selectMusicButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAudioFilePicker();
            }
        });
    }

    private void updateDetectionCount() {
        // 获取用户输入的检测次数
        String inputText = detectionCountInput.getText().toString();
        if (!inputText.isEmpty()) {
            detectionCount = Integer.parseInt(inputText);
        } else {
            detectionCount = 5;  // 如果用户未输入，使用默认值
        }
    }

    private void calculateBPM() {
        long currentTime = System.currentTimeMillis();

        if (lastTapTime > 0) {
            long interval = currentTime - lastTapTime;
            tapIntervals.add(interval);  // 添加间隔到列表中

            // 如果点击次数达到设定值，计算 BPM
            if (tapIntervals.size() >= detectionCount) {
                double bpm = calculateBPM(tapIntervals);
                bpmText.setText(String.format("%.2f", bpm));

                // 重置 tapIntervals 列表以重新开始记录
                tapIntervals.clear();
            }
        }

        lastTapTime = currentTime;
    }

    // 新的 calculateBPM 方法
    public double calculateBPM(List<Long> intervals) {
        if (intervals.isEmpty()) {
            return 0.0;
        }

        long totalInterval = 0;
        for (long interval : intervals) {
            totalInterval += interval;
        }

        long averageInterval = totalInterval / intervals.size();
        return 60000.0 / averageInterval;  // 从平均间隔计算 BPM
    }

    private void resetBPM() {
        lastTapTime = 0;
        tapIntervals.clear(); // 重置 tapIntervals 列表
        bpmText.setText("0");
    }

    private void openAudioFilePicker() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("audio/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(Intent.createChooser(intent, "Select Audio"), REQUEST_CODE_PICK_AUDIO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_AUDIO && resultCode == RESULT_OK && data != null) {
            Uri audioUri = data.getData();
            if (audioUri != null) {
                playSelectedAudio(audioUri);
            }
        }
    }

    private void playSelectedAudio(Uri audioUri) {
        if (mediaPlayer != null) {
            mediaPlayer.release();  // 释放之前的播放器资源
        }

        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(this, audioUri);
            mediaPlayer.prepare();
            mediaPlayer.setLooping(true); // 循环播放
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playClickSound() {
        if (clickSoundId != 0) {
            soundPool.play(clickSoundId, 1, 1, 0, 0, 1); // 播放点击音效
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        if (soundPool != null) {
            soundPool.release();
            soundPool = null;
        }
    }
}
